<template>
	<div class="about">
		<h1>{{id ? '编辑' : '新建'}}文章</h1>
		<el-form label-width="120px" v-on:submit.native.prevent="save">
			<el-form-item label="所属分类">
				<el-select v-model="model.categories" multiple><!-- categories是数组[],用in 结构[{_id:...,name:....},{_id:...,name:....}]-->
					<el-option
						v-for="item in categories"
						v-bind:key="item._id"
						v-bind:label="item.name"
						v-bind:value="item._id"
					></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="标题">
        <el-input v-model="model.title">
				</el-input>
      </el-form-item>
			<el-form-item label="内容">
				<!-- https://www.vue2editor.com/examples/#custom-image-handler -->
				<!-- 目的是减少上传图片的大小，转化为64字符，如果常规上传，一个图片10k以上，那这边文章用到很多图片就会消耗很多内存 -->
				<vue-editor v-model="model.content" useCustomImageHandler     @image-added="handleImageAdded"></vue-editor><!-- 改成image-added，不然不能上传图片 -->
      </el-form-item>
			<el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
		</el-form>
	</div>
</template>

<script>
/* eslint-disable */

// vueEditor属性对象中的某个属性
// 平时一般写 import a from ....这样的话要访问a.editor才能使用富文本编辑器
import { VueEditor } from 'vue2-editor'

export default {
	data(){
		return {
			model:{},
			categories:[]
		}
	},
	// 接收id，尽可能与路由解耦
	props:{
		id: {}
	},
	components:{
		 VueEditor
	},
	methods:{
		// https://www.vue2editor.com/examples/#custom-image-handler
		// es6写法，加上async
		// async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
		// 	const formData = new FormData()
		// 	formData.append("file", file)		//上传不了图片，后面才发现是上传格式不是image，是file（具体看物品或英雄图片上传时network的formData，拉最下面 formData: file :binary）,或者server/routes/admin/index.js中upload接收也是file
		// 	// 将formData上传，接口为upload（看server/routes/admin/index.js）,得到结果res，一个对象，里面很多属性，
		// 	// 省略了一些步骤，获取数据，赋值给res，获取url,插入图片，成功后resetUploader()，返回当前页面
		// 	const res = await this.$http.post("upload", formData)
		// 	Editor.insertEmbed(cursorLocation, "image", res.data.url)	//可以先打印res查看console.log(res)，官网写的是 let url = result.data.url （Get url from response）我们这样写就省略了步骤，基本不会失败
		// 	resetUploader();
		// },
		async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      const res = await this.$http.post("upload", formData);
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    },
		async save(){
			// console.log(this.id)
      let res
      if (this.id) {
        res = await this.$http.put(`rest/articles/${this.id}`, this.model)
      } else {
        res = await this.$http.post('rest/articles', this.model)
			}
			// const res = await this.$http.post('categories', this.model)
			// push要加/ 斜杠
			this.$router.push('/articles/list')
			this.$message({
        type: 'success',
        message: '保存成功'
      })
		},
		async fetch(){
      const res = await this.$http.get(`rest/articles/${this.id}`)
      this.model = res.data
		},
		async fetchCategories(){			//获取分类(这里要注意	)
			const res = await this.$http.get(`rest/categories`)
			this.categories = res.data
		}
	},
	created(){
		//	获取所有分类
		this.fetchCategories()
		// 存在id的情况下才执行fetch事件（编辑）
    this.id && this.fetch()
  }
}
</script>